new FastClick(document.body);
//封装cordova的执行方法，加上回调函数
var cordovaExec = function(plugin, action, parameters, callback) {
	//alert("进入cordovaExec方法");
	cordova.exec(function(data) {
		//alert("进入cordovaExec方法 success");
		if (callback !== undefined) {
			callback();
		}
	}, function(err) {
		//alert("进入cordovaExec方法 err ");
	}, plugin, action, parameters === null || parameters === undefined ? [] : parameters);
};
var backToMain = function() {
	$(".back_btn").trigger("click");
};

//首页接受到信息，刷新页面
var receiveMessage = function(identifier, count, display) {
	console.log("AAA进入index revceiveMessage count = " + count + identifier + display);
	var $moduleTips = $(".module_Tips[moduletype='main'][identifier='" + identifier + "']");
	console.log("size=" + $moduleTips.size());
	if (display && count > 0) {
		//alert(count);
		$moduleTips.html(count);
		$moduleTips.show();
	} else {
		$moduleTips.hide();
	}
	if (myScroll) {
		myScroll.refresh();
		//myScroll.scrollTo(0, 1, 200, true);
	}

};

//自动更新查新界面
var refreshMainPage = function(identifier, type, moduleMessage) {
	console.log("进入refreshMainPage" + type + "..." + identifier);
	if (localStorage.bslsessionKey) {
		console.log("有bslsessionKey");
		$('#login_btn').html("登出");
	} else {
		console.log("无bslsessionKey");
		$('#login_btn').html("登录");
	}
	if (($('.homeclick').hasClass('active')) && isOver === 0) {
		//主页面
		console.log("进入main页面");
		/*addModule(identifier, "main", moduleMessage);
		$("li[identifier='" + identifier + "']").css('opacity', '0.5');*/
		isOver = isOver + 1;
		console.log("刷新。。。。");
		loadModuleList("CubeModuleList", "mainList", "main", function() {
			//gridLayout();
			if (myScroll) {
				myScroll.refresh();
			}
			isOver = isOver - 1;
		});
	}

};

//改变登录按钮状态
// var isLogin = function(login) {
// 	if (login) {
// 		console.log("已经登录");
// 		$('#login_btn').html("登出");
// 	} else {
// 		console.log("已经登出");
// 		localStorage.removeItem("bslsessionKey");
// 		$('#login_btn').html("登录");
// 	}
// };

// $('.cube-flight-loader-cancel').bind("click", function() {
// 	$(".cube-flight-loader").hide();
// });
$("#login_btn").bind("click", function() {
	console.log("localStorage.bslsessionKey = " + localStorage.bslsessionKey);
	if (localStorage.bslsessionKey) {
		//alert("现在登出");
		var notifacation_onConfirm = function(buttonIndex) {
			if (buttonIndex == 1) {
				//alert("1");
				localStorage.removeItem("bslsessionKey");
				cordova.exec(function(plugindata) {
					console.log("bslse调用CubeLogoutPlugin");
					//$('#login_btn').html("登录");
					//console.log(plugindata);
				}, function() {

				}, "CubeLogoutPlugin", "logout", []);
			}
		};
		navigator.notification.confirm(
			'是否要登出？', // message
			notifacation_onConfirm, // callback to invoke with index of button pressed
			'提示', // title
			['确定', '取消'] // buttonLabels

		);



	} else {
		//alert("现在登录");
		//localStorage.bslsessionKey = "adfsdfasdfasfsdf";
		cordovaExec("CubeModuleOperator", "showModule", ["com.foss.phonelogin", "main"]);
	}


});

$(".homeclick").bind("click", function() {
	if (!$(this).hasClass("active")) {
		$(".tab-item").removeClass("active");
		$(this).addClass("active");
		$(".managerclick").html('<img src="img/manager_gray.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#666666;">管理</div>');
		$(".homeclick").html('<img src="img/home_orange.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#8d8d8d;">主页</div>');

		//$('#top_left_btn').removeClass('back_bt_class');
		//gridLayout();
		$('.buttomContent').css('display', 'none');
		$("#wrapper").css("top", "44px");

		$('#title').html("变色龙");
		$('#login_btn').show();

		loadModuleList("CubeModuleList", "mainList", "main", function() {
			gridLayout();
			if (myScroll) {
				myScroll.refresh();
				//$('#top_left_btn').removeClass("disabled");
			}

		});
	}

});
$(".managerclick").bind("click", function() {
	$(".tab-item").removeClass("active");
	$(this).addClass("active");
	$(".homeclick").html('<img src="img/home_gray.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#666666;">主页</div>');
	$(".managerclick").html('<img src="img/manager_orange.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#8d8d8d;">管理</div>');
	cordovaExec("CubeModuleOperator", "sync", [], function() {
		//alert("管理同步成功");

		//完成后设置listview
		$('.buttomContent').css('display', 'block');
		$("#wrapper").css("top", "94px");
		$('#title').html("模块管理");
		$('#login_btn').hide();
		console.log("listLayout");
		loadModuleList("CubeModuleList", "uninstallList", "uninstall", function() {
			listLayout();
			console.log("loadModuleList 数据完成");
			//$('.module_div ul li .curd_btn').css('display', 'inline');
			isOver = 0;
			var type = "uninstall";
			console.log("44");
			activeModuleManageBarItem(type);

			//cordovaExec("CubeModuleOperator", "manager");
			console.log("5");
			if (myScroll) {
				myScroll.refresh();
			}
			console.log("6");

		});
		console.log("同步成功");
		//myScroll.refresh();
	});


});
$(".settingclick").bind("click", function() {
	cordovaExec("CubeModuleOperator", "setting");
});

//进度获取
var updateProgress = function(identifier, count) {
	console.log(identifier + '进入updateProgress');
	if (count == -1) {
		$(".module_div ul li .module_li_img .progress[identifier='" + identifier + "']").css('display', 'block');
	} else if (count >= 0 && count <= 100) {

		console.log("count>=0 && count <=100 " + count);

		$(".module_div ul li .module_li_img .progress[identifier='" + identifier + "']").css('display', 'block');

		$(".module_div ul li .module_li_img .progress[identifier='" + identifier + "'] .bar").css('width', count + "%");



	} else if (count == 101) {
		$(".module_div ul li .module_li_img .progress[identifier='" + identifier + "']").css('display', 'none');

	}

};

//模块增删，刷新模块列表(uninstall，install，upgrade)
var refreshModule = function(identifier, type, moduleMessage) {
	if ($('.managerclick').hasClass('active')) {
		console.log("进入refreshModule " + type + "..." + identifier);

		if (type === "uninstall") {
			console.log("进入uninstall");
			//已安装减一个
			console.log("已安装页面减一个");
			$(".module_li[moduletype='install'][identifier='" + identifier + "']").remove();
			if ($("#uninstallBtn").hasClass("active")) {
				//未安装加一个
				addModule(identifier, "uninstall", moduleMessage);
				console.log("未安装的加一个成功");
			}

			//更新有则减

			$(".module_li[moduletype='upgrade'][identifier='" + identifier + "']").remove();
		} else if (type === "install") {
			console.log("进入install");
			//未安装减一个
			$(".module_li[moduletype='uninstall'][identifier='" + identifier + "']").remove();
			$(".module_li[moduletype='upgrade'][identifier='" + identifier + "']").remove();
			if ($("#installBtn").hasClass("active")) {
				//已安装加一个
				addModule(identifier, "install", moduleMessage);
			}


			//更新不变
		} else if (type === "upgrade") {
			//更新减一个
			$(".module_li[moduletype='upgrade'][identifier='" + identifier + "']").remove();
			//已安装替换
			//addModule(identifier, "install", moduleMessage);

			//未安装不变
		} else if (type === "main") {
			//addModule(identifier, "main", moduleMessage);
		}


	} else {
		//主页面
		console.log("主界面、、");
		//$("li[identifier='" + identifier + "']").css('opacity', '1');
		//判断模块 hidden
		var isHidden = $("li[identifier='" + identifier + "']").attr("hidden");
		console.log("是否显示？？？？" + isHidden);
		if (isHidden == "true") {
			$("li[identifier='" + identifier + "']").remove();
		}
	}
	checkModules();


};
var addModule = function(identifier, type, moduleMessage) {
	var mm = moduleMessage;
	if (!(moduleMessage instanceof Object)) {
		mm = $.parseJSON(moduleMessage);
	}

	var isuninstallpage = false;
	if ($(".managerclick").hasClass("active") && $("#uninstallBtn").hasClass("active")) {
		isuninstallpage = true;
	}
	//如果该模块不存在，则生成
	if ($(".scrollContent_li[modules_title='" + mm.category + "']").size() < 1) {
		var tag = $(".scrollContent_li").size();
		//获取模板名
		var moduleContentTemplate = $("#t2").html();

		var moduleContentHtml = _.template(moduleContentTemplate, {
			'muduleTitle': mm.category,
			"tag": tag
		});
		$(".mainContent").find(".scrollContent").append(moduleContentHtml);
	}


	//如果存在，先删除，再添加
	if ($("li[identifier='" + identifier + "']").size() > 0) {

		$("li[identifier='" + identifier + "']").remove();


	}

	var moduleItemTemplate = $("#module_div_ul").html();

	//更新的图标，如果在未安装里面，不应该出现
	if (type === 'uninstall') {
		mm.updatable = false;
	}

	mm.name = subStrByCnLen(mm.name + "", 9);

	if ($('.homeclick').hasClass('active')) {
		mm.name = subStrByCnLen(mm.name + "", 5);
	}
	var privileges = "null";
	if (mm.privileges) {
		console.log("privileges存在");
		privileges = mm.privileges;
	} else {
		console.log("privileges不存在");
	}

	mm.releaseNote = subStrByCnLen(mm.releaseNote + "", 13);

	console.log("privileges -----" + privileges);
	var moduleItemHtml = _.template(moduleItemTemplate, {
		'icon': mm.icon,
		'name': mm.name,
		'moduleType': type,
		'identifier': mm.identifier,
		'version': mm.version,
		'releasenote': mm.releaseNote,
		'btn_title': changeBtnTitle(type),
		"updatable": mm.updatable,
		"local": mm.local,
		"msgCount": mm.msgCount,
		"hidden": mm.hidden,
		"privileges": privileges,
		"isuninstallpage": isuninstallpage
	});
	$(".scrollContent_li[modules_title='" + mm.category + "']").children('div').children('ul').append(moduleItemHtml);


	if (myScroll) {
		myScroll.refresh();
	}



};
//检查模块信息的完整性，如果没有模块，则隐藏
var checkModules = function() {
	console.log('AAAAAA----检查模块信息的完整性，如果没有模块，则隐藏');
	$.each($(".scrollContent_li"), function(index, data) {

		if ($(this).children('.module_div').children('.module_div_ul').children('.module_li').size() < 1) {
			$(this).remove();

		} else {
			var show_module_lis = $(this).children('.module_div').children('.module_div_ul').children('.module_li');
			$.each($(show_module_lis), function(i, show_module_li) {
				if ($(show_module_li).css('display') == "none") {
					console.log("有隐藏的对象");
					$(show_module_li).parent('.module_div_ul').parent('.module_div').parent('.scrollContent_li').remove();

				}
			});

		}

	});

};

var changeBtnTitle = function(type) {
	//alert("进入changeBtnTitle");
	switch (type) {
		case "install":
			return "删除";
			break;
		case "uninstall":
			return "安装";
			break;
		case "upgradable":
			return "更新";
			break;
		case "upgrade":
			return "更新";
			break;
		case "main":
			return "删除";
			break;

	}
	//alert("完成changeBtnTitle");
};
/*$(document).ready(function() {*/
// 选中模块操作菜单，传入需要激活的按钮名称（uninstall，install，upgrade）
var activeModuleManageBarItem = function(type) {
	// 移除所有选中
	$(".buttomContent .buttom_btn_group .btn").removeClass("active");
	// 选中当前点击
	$(".buttomContent .buttom_btn_group .btn[data='" + type + "']").addClass("active");
};

//点击模块的时候触发事件
var module_all_click = function() {
	$("li[identifier]").live('click', function() {
		var type = $(this).attr("moduleType");
		var identifier = $(this).attr("identifier");
		//var privileges = $(this).attr("privileges");
		console.log("AAAAAmodule_all_click----" + type + " == " + identifier);
		cordovaExec("CubeModuleOperator", "showModule", [identifier, type]);

		// if (privileges != null && privileges !== "null") {
		// 	//有权限
		// 	//alert("有权限 showModule");
		// 	console.log("AAAAAmodule_all_click----" + type + " == " + identifier + "==" + privileges);
		// 	cordovaExec("CubeModuleOperator", "showModule", [identifier, type]);
		// } else {
		// 	//没权限

		// 	if ($(".homeclick").hasClass("active")) {
		// 		var notifacation_onConfirm = function(buttonIndex) {
		// 			if (buttonIndex == 1) {
		// 				//alert("1");
		// 				cordovaExec("CubeModuleOperator", "showModule", ["com.foss.phonelogin", "main"]);
		// 			}
		// 		};
		// 		if (localStorage.bslsessionKey) {
		// 			// var r = confirm("没权限，请切换用户！");
		// 			// if (r == true) {

		// 			// 	cordovaExec("CubeModuleOperator", "showModule", ["com.foss.phonelogin", "main"]);
		// 			// };

		// 			navigator.notification.confirm(
		// 				'没有权限，请切换用户！', // message
		// 				notifacation_onConfirm, // callback to invoke with index of button pressed
		// 				'提示', // title
		// 				['确定', '取消'] // buttonLabels

		// 			);



		// 		} else {
		// 			navigator.notification.confirm(
		// 				'没有权限，请登录！', // message
		// 				notifacation_onConfirm, // callback to invoke with index of button pressed
		// 				'提示', // title
		// 				['确定', '取消'] // buttonLabels

		// 			);

		// 		}



		// 	} else {
		// 		//alert("没权限 模块管理");
		// 		console.log("AAAAAmodule_all_click----" + type + " == " + identifier + "==" + privileges);
		// 		cordovaExec("CubeModuleOperator", "showModule", [identifier, type]);
		// 	}


		// 	//window.location.href = "../com.foss.phonelogin/index.html";
		// }



	});
};



var changeLayout = function(oldfilename, newfilename, type) {
	//replacejscssfile("css/gridview.css", "css/listview.css", "css");
	replacejscssfile(oldfilename, newfilename, type);
}



// 加载列表，渲染成html
var isOver = 0;
var loadModuleList = function(plugin, action, type, callback) {
	console.log('AAAAAA------------------ZHE');
	cordova.exec(function(data) {
		//alert("loadModuleList 获取底层数据成功");
		data = $.parseJSON(data);
		console.log("AAAAAAAA initial=" + type);
		//alert("initial start");
		//alert("进入initial");
		console.log(data);
		var i = 0;
		$('.temul').html("");
		var isuninstallpage = false;
		if ($(".managerclick").hasClass("active") && $("#uninstallBtn").hasClass("active")) {
			isuninstallpage = true;
		}
		_.each(data, function(value, key) {
			console.log("--------------key= " + key);
			//alert("一个分类");
			console.log(value);
			// if (i == 0) {
			// 	$("#myul").html("");
			// }
			$('.temul').append(_.template($("#t2").html(), {
				'muduleTitle': key,
				'tag': i
			}));
			_.each((value), function(value, key) {
				console.log("value name  " + value.name + " ------------------------------------------------------------------------------");
				//更新的图标，如果在未安装里面，不应该出现
				if (type === 'uninstall') {
					value.updatable = false;
				}

				value.name = subStrByCnLen(value.name + "", 9);
				if ($('.homeclick').hasClass('active')) {
					value.name = subStrByCnLen(value.name + "", 5);
				}
				var privileges = "null";
				if (value.privileges) {
					console.log("privileges存在");
					privileges = value.privileges;
				} else {
					console.log("privileges不存在");
				}
				//alert(privileges);



				value.releaseNote = subStrByCnLen(value.releaseNote + "", 13);
				$('.module_div_ul[num="' + i + '"]').append(
					_.template($("#module_div_ul").html(), {
						'icon': value.icon,
						'name': value.name,
						'moduleType': type,
						'identifier': value.identifier,
						//'version': value.version,
						'releasenote': value.releaseNote,
						'btn_title': changeBtnTitle(type),
						"updatable": value.updatable,
						"local": value.local,
						"msgCount": value.msgCount,
						"hidden": value.hidden,
						"privileges": privileges,
						"isuninstallpage": isuninstallpage
					}));
			});


			i = i + 1;
		});

		$(".myul").html($(".temul").html());
		$(".temul").html("");

		$(".mainContent").css('padding-bottom', '20px');



		i = 0;
		console.log("完成initial方法");


		$("li[identifier]").die("click");
		module_all_click();

		if (myScroll) {
			myScroll.refresh();
		}

		checkModules();
		//如果回调方法不为空，则执行该回调方法
		if (callback !== undefined) {
			callback();
		}
		console.log("完成loadMuduleList");
	}, function(err) {
		isOver = isOver - 1;
	}, plugin, action, []);

	//}



};
// 左边按键--设置、返回
// $('#top_left_btn')
// 	.bind("click",
// 		function() {
// 			$('#top_left_btn').addClass("disabled");
// 			isOver = 0;
// 			if ($(this).hasClass('back_bt_class')) {
// 				// 返回按键

// 				$('#top_left_btn').removeClass('back_bt_class');
// 				gridLayout();
// 				////alert("shanchu le back_bt_class");
// 				$('.buttomContent').css('display', 'none');
// 				$("#wrapper").css("top", "44px");

// 				$('#title').html("变色龙");
// 				$('#manager_btn').show();
// 				$('#top_left_btn').addClass("left_btn");
// 				$('#top_left_btn').removeClass("back_btn");

// 				//cordovaExec("CubeModuleOperator", "index");
// 				loadModuleList("CubeModuleList", "mainList", "main", function() {
// 					if (myScroll) {
// 						myScroll.refresh();
// 						$('#top_left_btn').removeClass("disabled");
// 					}

// 				});


// 			} else {

// 				// 设置按键
// 				$('#top_left_btn').removeClass("disabled");
// 				cordovaExec("CubeModuleOperator", "setting");
// 			}


// 		});


// 检测屏幕是否伸缩
// var LastHeight = window.screen.availHeight;
// $(window).resize(function() {
// 	var browser = navigator.appName;
// 	if (browser !== "Microsoft Internet Explorer") {
// 		var availHeight = $(window).height();
// 		console.log("LastHeight " + LastHeight);
// 		console.log("availHeight " + availHeight);
// 		if (Math.abs(LastHeight - availHeight) > 100) {
// 			if ((LastHeight - availHeight) > 0) {
// 				//键盘弹出
// 				console.log("键盘弹出了");

// 				$('.buttomContent').hide();
// 			} else {
// 				console.log("键盘隐藏了。。。");
// 				//键盘隐藏
// 				if ($('#top_left_btn').hasClass('back_bt_class')) {
// 					$('.buttomContent').show();
// 				}
// 			}
// 		}
// 		LastHeight = availHeight;
// 		if (myScroll) {
// 			myScroll.refresh();
// 		}
// 	}


// });
$("#wrapper").bind("touchend", function() {
	if (myScroll) {
		myScroll.refresh();
	}

});

var listLayout = function() {

	console.log("listview");
	changeLayout("css/gridview.css", "css/listview.css", "css");

	setTimeout(function() {
		if (myScroll) {
			myScroll.refresh();
			myScroll.scrollTo(0, 0, 200, false);
		}

	}, 100);
};

var gridLayout = function() {
	console.log("gridview");
	changeLayout("css/listview.css", "css/gridview.css", "css");


	$("li[identifier]").css("background", "#ffffff");

	//设置titlename位置
	$('.detail .module_li_titlename').css('font-size', '0.9em').css("top", "10px");

	setTimeout(function() {
		if (myScroll) {
			myScroll.refresh();
			//myScroll.scrollTo(0, 0, 200, false);
		}

	}, 100);
}


// 管理按钮
// $('#manager_btn')
// 	.click(function() {
// 		$('#manager_btn').addClass("disabled");
// 		console.log("点击");

// 		cordovaExec("CubeModuleOperator", "sync", [], function() {
// 			//alert("管理同步成功");
// 			//完成后设置listview
// 			$('.buttomContent').css('display', 'block');
// 			$("#wrapper").css("top", "94px");
// 			$('#title').html("模块管理");

// 			console.log("listLayout");
// 			loadModuleList("CubeModuleList", "uninstallList", "uninstall", function() {
// 				//listLayout();
// 				console.log("loadModuleList 数据完成");
// 				$('.module_div ul li .curd_btn').css('display', 'inline');
// 				isOver = 0;
// 				var type = "uninstall";
// 				console.log("44");
// 				activeModuleManageBarItem(type);

// 				//cordovaExec("CubeModuleOperator", "manager");
// 				console.log("5");
// 				if (myScroll) {
// 					myScroll.refresh();
// 				}
// 				console.log("6");

// 			});
// 			console.log("同步成功");
// 			//myScroll.refresh();
// 		});
// 		//$('#manager_btn').removeClass("disabled");
// 	});


//处理底下按钮
$(".buttomContent .buttom_btn_group .btn").click(function() {
	var type = $(this).attr("data");
	console.log("butom type=" + type);
	if (!$(this).hasClass("active")) {
		activeModuleManageBarItem(type);
		var t = type;
		if (type == "upgrade") {
			type = "upgradable";
		}

		loadModuleList("CubeModuleList", type + "List", t, function() {
			//listLayout();
			if (myScroll) {
				myScroll.refresh();
			}

		});

	}

});


//---------------------------------------------------------------------------------------------


//应用初始化
var app = {
	initialize: function() {

		this.bindEvents();
	},
	bindEvents: function() {

		document.addEventListener('deviceready', this.onDeviceReady, false);
		/*var browser = navigator.appName;
		if (browser !== "Microsoft Internet Explorer") {
			new FastClick(document.body);
		}*/
	},
	onDeviceReady: function() {

		app.receivedEvent('deviceready');
	},
	receivedEvent: function(id) {
		console.log("receivedEvent");
		if (localStorage.bslsessionKey) {
			localStorage.removeItem("bslsessionKey");
		}
		loadModuleList("CubeModuleList", "mainList", "main", function() {
			cordovaExec("CubeModuleOperator", "sync", [], function() {
				console.log("同步成功");
				loadModuleList("CubeModuleList", "mainList", "main", function() {
					if (myScroll) {
						myScroll.refresh();

					}
				});
			});
		});

	}
};
app.initialize();